<?php
namespace app\admin\controller\account;

use app\admin\BaseController;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupRule;
use app\lib\exception\FailedException;
use app\lib\exception\NotFoundException;
use app\lib\exception\ParameterException;
use app\Validate\AccountTypeMustPositiveValidate;
use app\Validate\AdminActionValidate;
use app\Validate\AuthGroupValidate;
use app\Validate\IdMustPositive;
use app\Validate\PageMustValidate;

use Payment\Client\Charge;
use Payment\Common\PayException;
use think\Db;
use think\Request;


class Admin extends BaseController
{
    protected $model = '';

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\common\validate\Admin();
        $this->admin_model = new \app\admin\model\Admin();
    }

    /**
     * 获取账号列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function getAdminList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where =[];
        $where[] = ['pid','eq',$post['admin_id']];
        $where = addWhere($post,['role_id'=>'','account_type'=>''],$where,1);//角色id  //账号类型
        $where = addWhere($post,['username'=>''],$where,2);//用户名
        $count = (new \app\admin\model\Admin())->getCount($where);

        $where['page'] = isset($post['page']) ? $post['page'] : 1;
        $per_page_number = isset($post['page_number']) ? $post['page_number'] : 15;

        $adminList = (new \app\admin\model\Admin())->wechatListWith("role,admin",$where,"*",'',$per_page_number);
        $returnData = [
          'dataList' => $adminList,
          'count' => $count
        ];
        return writeJson(200,$returnData);
    }

    /**
     * 添加账号
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function adminAdd(Request $request){
        try {
            $config = require_once  ALI_PATH."aliconfig.php";
            $info = [
                'body'=>'商品信息',
                'subject'=>'测试商品',
                'order_no'=>'10000',
                'amount' =>100,

            ];
            //$res=  Charge::run("ali_app",$config,$info);
            //echo $res;
        } catch (PayException $e) {
            echo $e->errorMessage();
            exit;
        }

        (new AdminActionValidate())->goCheck();
        $post = $request->post();
        if(!isset($post['password'])){
            throw  new ParameterException(['msg'=>'缺少password']);
        }
        if(!isset($post['account_type'])){
            throw  new ParameterException(['msg'=>'缺少账号类型']);
        }
        $admin = (new \app\admin\model\Admin())->findOne([['id','eq',$post['admin_id']],['status','eq',1]]);
        //查询账号是否存在
        $count = (new \app\admin\model\Admin())->getCount([['account','eq',$post['account']]]);
        if($count>0){
            throw  new NotFoundException(['msg'=>'账号已存在']);
        }
        if(!isMobilephone($post['phone'])){
            throw  new FailedException(['msg'=>'手机号格式错误']);
        }

        $role = (new AuthGroup())->findOne([['id','eq',$post['role_id']],['admin_id','eq',$post['admin_id']]]);
        if(!$role){
            throw  new NotFoundException(['msg'=>'所属角色不存在']);
        }
        $new = [
            'account_type'=>$post['account_type'],
            'username'=>$post['username'],
            'password'=>md5($post['password']),
            'account' =>$post['account'],
            'phone' =>$post['phone'],
            'uid'   =>$admin['uid'],
            'pid'   =>$post['admin_id'],
            'rank'  =>$admin['rank']+1,
            'role_id'=>$post['role_id']
        ];
        $res = (new \app\admin\model\Admin())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'添加失败']);
        }
        return writeJson(200,[],'操作成功');
    }

    /**
     * 编辑账号
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function adminEdit(Request $request){
        (new AdminActionValidate())->goCheck();
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        //查询账号是否存在
        $count = (new \app\admin\model\Admin())->getCount([['account','eq',$post['account']],['id','neq',$post['id']]]);
        if($count>0){
            throw  new NotFoundException(['msg'=>'账号已存在']);
        }
        if(!isMobilephone($post['phone'])){
            throw  new FailedException(['msg'=>'手机号格式错误']);
        }
        $role = (new AuthGroup())->findOne([['id','eq',$post['role_id']],['admin_id','eq',$post['admin_id']]]);
        if(!$role){
            throw  new NotFoundException(['msg'=>'所属角色不存在']);
        }
        $admin = (new \app\admin\model\Admin())->findOne([['id','eq',$post['admin_id']],['status','eq',1]]);
        $new = [
            'id'     =>$post['id'],
            'username'=>$post['username'],
//            'password'=>md5($post['password']),
            'account' =>$post['account'],
            'phone' =>$post['phone'],
            'uid'   =>$admin['uid'],
            'pid'   =>$post['admin_id'],
            'rank'  =>$admin['rank']+1,
            'role_id'=>$post['role_id'],
            'account_type'=>$post['account_type']
        ];

        $res = (new \app\admin\model\Admin())->dataUpdate($new);
        if(!$res){
            throw new FailedException(['msg'=>'修改失败']);
        }
        return writeJson(200,[],'操作成功');
    }

    /**
     * 获取角色列表
     * @param Request $request
     * @return \think\response\Json
     * @throws \app\lib\exception\ParameterException
     */
    public function getGroupList(Request $request){
        (new PageMustValidate())->goCheck();
        $post = $request->post();
        $where =[];
        $where[] = ['admin_id','eq',$post['admin_id']];
        $where = addWhere($post,['title'=>''],$where,2);//用户名
        $where = addWhere($post,['account_type'=>''],$where,1);//角色类型
        $count = (new AuthGroup())->getCount($where);
        $where['page'] = $post['page'];
        $adminList = (new AuthGroup())->wechatList($where,"*","id desc",$post['page_number']);
        foreach ($adminList as &$value){
            $value['ruleList'] = (new AuthGroupRule())->where('role_id',$value['id'])->column("rule_id");
            $value['num'] = (new \app\admin\model\Admin())->where('role_id',$value['id'])->count();
        }
        $returnData = [
            'dataList' =>$adminList,
            'count' =>$count
        ];
        return writeJson(200,$returnData);
    }

    /**
     * 添加角色
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function authGroupAdd(Request $request){
        (new AuthGroupValidate())->goCheck();
        $post = $request->post();
        $admin = (new AuthGroup())->findOne([['id','eq',$post['admin_id']],['status','eq',1]]);
        $new = [
            'account_type' =>$post['account_type'],
            'admin_id'=>$post['admin_id'],
            'uid'=>$admin['uid'],
            'title'=>$post['title'],
            'description'=>$post['description'],
        ];
        Db::startTrans();
        $res = (new AuthGroup())->dataUpdate($new);
        if(!$res){
            Db::rollback();
            throw new FailedException(['msg'=>'添加失败']);
        }
        $new = [];
        foreach ($post['ruleList'] as $value){
            $new[] =[
              'role_id'=>$res,
              'rule_id'=>$value
            ];
        }
        $result = (new AuthGroupRule())->saveAll($new);
        if(!$result){
            Db::rollback();
            throw new FailedException(['msg'=>'添加关联失败']);
        }
        Db::commit();
        return writeJson(200,[],'操作成功');
    }

    /**
     * 查询角色下面的权限
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function authGroupRule(Request $request){
        (new AccountTypeMustPositiveValidate())->goCheck();
        $post = $request->post();
        //$auth  = getAdminAuth(3,$post['account_type']);
        $auth = [];
        $level = 3;
        $where_auth = [
            ['type','elt',$level],
//            ['account_type','eq',$post['account_type']]
        ];
        $user_info = (new \app\admin\model\Admin())->where([['id','eq',$post['admin_id']]])->find();
        //$rule_model = new AuthRule();
        $group_rule_model = new AuthGroupRule();
        $rule_id = $group_rule_model->where(['role_id'=>$user_info['role_id']])->column('rule_id');
        if($user_info['rank']!=1){
            $where_auth[] = ['id','in',$rule_id];
        }
        $list = (new \app\admin\model\AuthRule())->selectList($where_auth,"id,pid,title,rule_val,rule_url,account_type,type","sort desc");
        $list = $list->toArray();
        foreach ($list as $value){
            if($value['type']==1){
                if($level>=2){
                    $value['itemList'] = [];
                }
                $auth[$value['id']] = $value;
            }
        }
        if($level>=2){
            foreach ($list as $value){
                if($value['type']==2){
                    if($level>=3){
                        $value['itemList'] = [];
                    }
                    $auth[$value['pid']]['itemList'][$value['id']] = $value;
                }
            }
        }
        if($level>=3){
            foreach ($list as $value){
                if($value['type']==3){
                    foreach ($auth as &$val){
                        if(isset($val['itemList'][$value['pid']])){
                            $val['itemList'][$value['pid']]['itemList'][] = $value;
                        }
                    }
                }
            }
        }
        foreach ($auth as &$value){
            if(isset($value['itemList'])){
                $value['itemList']=array_values($value['itemList']);
            }
        }
        $auth = array_values($auth);
        return writeJson(200,['auth'=>$auth]);
    }

    /**
     * 编辑角色
     * @param Request $request
     * @return \think\response\Json
     * @throws FailedException
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function authGroupEdit(Request $request){
        (new AuthGroupValidate())->goCheck();
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $admin = (new AuthGroup())->findOne([['id','eq',$post['id']],['status','eq',1]]);

        if(!$admin){
            throw new NotFoundException(['msg'=>'当前登录账号不存在或被封停']);
        }
        $new = [
            'id'     =>$post['id'],
            'title'=>$post['title'],
            'description' =>$post['description'],
            'account_type'=>$post['account_type']
        ];
        Db::startTrans();
        $res = (new AuthGroup())->dataUpdate($new);
        if(!$res){
            Db::rollback();
            throw new FailedException(['msg'=>'修改失败']);
        }
        (new AuthGroupRule())->where("role_id",$post['id'])->delete();
        $new = [];
        foreach ($post['ruleList'] as $value){
            $new[] =[
                'role_id'=>$res,
                'rule_id'=>$value
            ];
        }
        $result = (new AuthGroupRule())->saveAll($new);
        if(!$result){
            Db::rollback();
            throw new FailedException(['msg'=>'添加关联失败']);
        }
        Db::commit();
        return writeJson(200,[],'操作成功');
    }

    /**
     * 删除角色
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function authGroupDelete(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $admin = (new AuthGroup())->findOne([['id','eq',$post['id']],['status','eq',1]]);
        if(!$admin){ throw new NotFoundException(['msg'=>'当前登录账号不存在或被封停']); }
        (new AuthGroup())->where("id",$post['id'])->delete();
        (new AuthGroupRule())->where("role_id",$post['id'])->delete();
        return writeJson(200,[],'操作成功');
    }

    /**
     * 删除账号
     * @param Request $request
     * @return \think\response\Json
     * @throws NotFoundException
     * @throws \app\lib\exception\ParameterException
     */
    public function adminDelete(Request $request){
        (new IdMustPositive())->goCheck();
        $post = $request->post();
        $admin = (new \app\admin\model\Admin())->findOne([['id','eq',$post['id']]]);
        if(!$admin){ throw new NotFoundException(['msg'=>'当前登录账号不存在或被封停']); }
        (new \app\admin\model\Admin())->where("id",$post['id'])->delete();
        return writeJson(200,[],'操作成功');
    }
}